import WebIM from '../components/chat/WebIM';

const conn = WebIM.conn;

const open = (options,callBacks)=>{
    console.log('打开连接',options,callBacks);
    const onOpened = callBacks.onOpened;
    const onError = callBacks.onError;
    delete callBacks.onOpened;
    delete callBacks.onError;
    return new Promise((resolve,reject)=>{
        WebIM.conn.open(options);
        WebIM.conn.listen({
            onOpened:(e)=>{
                conn.setPresence();
              if(typeof onOpened === 'function'){
                  onOpened(e);
                  console.log('onOpened',e);
              }
                resolve(e);
            },
            onError:(e)=>{
                console.log('onError',e);
                if(typeof onError === 'function'){
                    onError(e);

                }
                reject(e);
            },
            ...callBacks
        });
    })
};
const sendMessage = (options,callBacks)=>{
    console.log('发送消息',options);
    const id = conn.getUniqueId();// 生成本地消息id
    const type = options.type;
    const data = options.data;
    const msg = new WebIM.message(type, id);
    if(type === 'txt'){
        options.msg = data;
    }
    if (type === 'img'){
        options.ext = data.ext;
        options.file = data.file;
        delete options.data;
    }
    if (type === 'audio'){
        options.file = data.file;
        delete options.data;
    }
    msg.body.chatType = 'singleChat';
    return new Promise((resolve,reject)=>{
        msg.set({
            ...options,
            success:(id,serverMsgId)=>{resolve({id,serverMsgId})},
            fail:(e)=>{reject(e)}
        });
        conn.send(msg.body);
    })
};



export default  {
    open,
    sendMessage,
}
